package com.online.pay.common.sign;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * 
 * @author wuhang
 *
 */
public class StringUtils {
	/**
	 * 判定字符串是否为空
	 * <p>
	 * Checks if a CharSequence is whitespace, empty ("") or null.
	 * </p>
	 *
	 * <pre>
	 * StringUtils.isBlank(null)      = true
	 * StringUtils.isBlank("")        = true
	 * StringUtils.isBlank(" ")       = true
	 * StringUtils.isBlank("bob")     = false
	 * StringUtils.isBlank("  bob  ") = false
	 * </pre>
	 *
	 * @param cs
	 *            the CharSequence to check, may be null
	 * @return {@code true} if the CharSequence is null, empty or whitespace
	 * @since 2.0
	 * @since 3.0 Changed signature from isBlank(String) to
	 *        isBlank(CharSequence)
	 */
	public static boolean isBlank(CharSequence cs) {
		int strLen;
		if (cs == null || (strLen = cs.length()) == 0) {
			return true;
		}
		for (int i = 0; i < strLen; i++) {
			if (Character.isWhitespace(cs.charAt(i)) == false) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 去除报文中的空格、回车、换行符、制表符，但保留xml的报文头
	 * 
	 * @param str
	 *            - 等待处理的报文
	 * @return 除格式后的报文
	 */
	public static String replaceXMLBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
			dest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + dest.substring(36);
		}
		return dest;
	}

	/**
	 * 替换xml中节点的值，只适合替换报文中只有一个指定名字的节点
	 * 
	 * @param nodeStart
	 *            节点开始标签 eg :&lt;TransactionID&gt;
	 * @param nodeEnd
	 *            节点结束标签 eg :&lt;/TransactionID&gt;
	 * @param relacement
	 *            节点替换的内容
	 * @param xml
	 *            原字符串
	 * @return 替换后的字符串
	 */
	public static String relaceNodeContent(String nodeStart, String nodeEnd, String relacement, String xml) {
		int nodeStartLength = nodeStart.length();
		int start = xml.indexOf(nodeStart);
		int end = xml.indexOf(nodeEnd);

		if (start > -1 && end > -1) {
			String segStart = xml.substring(0, start + nodeStartLength);
			String segEnd = xml.substring(end, xml.length());
			return segStart + relacement + segEnd;
		}
		return xml;
	}

	/**
	 * 以字符串查找的试获取xml文本中节点的值
	 * 
	 * @param nodeStart
	 *            节点开始标签 eg :&lt;TransactionID&gt;
	 * @param nodeEnd
	 *            节点结束标签 eg :&lt;/TransactionID&gt;
	 * @param src
	 *            原字符串
	 * @return 节点值
	 */
	public static String parseNodeValueFromXml(String nodeStart, String nodeEnd, String src) {
		int nodeStartLength = nodeStart.length();
		int start = src.indexOf(nodeStart);
		int end = src.indexOf(nodeEnd);
		if (start > -1 && end > -1) {
			return src.substring(start + nodeStartLength, end);
		}
		return "";
	}
}
